package com.zp.util;

import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.Writer;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

/**
 * encapsulation XML util
 * 
 * @version 1.0
 * 
 * @author chenlijun08@gmail.com
 * 
 */
public class Dom4JUtil {

	/**
	 * generate XML file with file name
	 * 
	 * @param fileName
	 *            file name
	 */
	public static void createXml(String fileName) {
		Document document = DocumentHelper.createDocument();
		Element employees = document.addElement("Testing");
		Element employee = employees.addElement("Test");
		Element name = employee.addElement("name");
		name.setText("ddvip");
		Element sex = employee.addElement("sex");
		sex.setText("m");
		Element age = employee.addElement("age");
		age.setText("29");
		try {
			Writer fileWriter = new FileWriter(fileName);
			XMLWriter xmlWriter = new XMLWriter(fileWriter);
			xmlWriter.write(document);
			xmlWriter.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	/**
	 * parser special file name
	 * 
	 * @param fileName
	 */
	@SuppressWarnings("rawtypes")
	public static Map<String, String> parserXml(String fileName) {
		Map<String, String> map = new HashMap<String, String>();
		InputStream inputStream = Dom4JUtil.class
				.getResourceAsStream("/configure/" + fileName);
		SAXReader saxReader = new SAXReader();
		try {
			Document document = saxReader.read(inputStream);
			Element elements = document.getRootElement();
			for (Iterator i = elements.elementIterator(); i.hasNext();) {
				Element node = (Element) i.next();
				map.put(node.getName(), node.getText());
			}
		} catch (DocumentException e) {
			System.out.println(e.getMessage());
		}
		return map;
	}
}